function ajax(time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (time === 1000) {
        reject();
      }
      resolve();
    }, time);
  });
}

// ajax(1000).then(res => {
//     console.log(res);
// })
// ajax(2000).then(res => {
//     console.log(res);
// })
// ......

// 控制并发数量为2

class Limit {
  constructor(limit = 2) {
    this.limit = limit;
    this.queue = [];
    this.count = 0;
  }
  add(fn) {
    return new Promise((resolve, reject) => {
      this.queue.push({
        fn,
        resolve,
        reject,
      });
      this._run();
    });
  }
  _run() {
    while (this.count < this.limit && this.queue.length) {
      const { fn, resolve, reject } = this.queue.shift();
      this.count++;
      fn()
        .then(resolve, reject)
        .finally(() => {
          this.count--;
          this._run();
        });
    }
  }
}

const limit = new Limit(2);
function addTask(time, name) {
  limit.add(() => ajax(time))
    .then(() => {
      console.log(`任务${name}完成`);
    })
    .catch((err) => {
      console.log(`任务${name}失败`);
      console.log(err);
    });
}

addTask(10000, 1);
addTask(5000, 2);
addTask(1000, 3);
addTask(3000, 4);
addTask(4000, 5);
